//
//  HSVideoPlayViewController.m
//  ZFPlayer_Example
//
//  Created by 紫枫 on 2019/6/5.
//  Copyright © 2019 紫枫. All rights reserved.
//

#import "HSVideoPlayViewController.h"
#import "HSCustomControlView.h"
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/UIView+ZFFrame.h>
#import <ZFPlayer/ZFPlayerConst.h>
#import "UIImageView+ZFCache.h"
#import "ZFUtilities.h"
#import "XHComMacro.h"
#import "UIImage+ImageEffects.h"
#import "PlayVideoTableViewCell.h"
#import "ObjectAFNetWorking.h"
#import "Common.h"
#import "Cache.h"
#import "FKLastPlayMedia.h"
static NSString *kVideoCover = @"https://upload-images.jianshu.io/upload_images/635942-14593722fe3f0695.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";

@interface HSVideoPlayViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) UIImageView *containerView;
@property (nonatomic, strong) HSCustomControlView *controlView;
@property (nonatomic, strong) UITableView *directoryTableView;
@property (nonatomic, strong) UIButton *audioBtn;
@property (nonatomic, strong) UIButton *videoBtn;
@property (nonatomic, weak) UIView *tabLineView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) ObjectAFNetWorking* objectAFN;
@property (nonatomic, strong) ZFAVPlayerManager *playerManager;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSArray *playUrls;
@property (nonatomic, weak) UIButton *playOrderBtn; // “播放顺序”按钮
@property (nonatomic, strong) UIButton *playModeBtn; // “播放模式”按钮
@property (nonatomic, assign) NSInteger playStyle;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, weak) UILabel* desLabel;
@property(nonatomic, strong) UIButton *likeBtn;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, assign) NSTimeInterval duration;

@end

@implementation HSVideoPlayViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self setNavigationBarHidden];
    self.player.viewControllerDisappear = NO;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.objectAFN = [[ObjectAFNetWorking alloc]init];
    // 初始化头部
    [self initTopView];
    // 添加视频的容器view
    [self.view addSubview:self.containerView];
    // 初始化中间部分
    [self initMiddleView];
    // 加载数据
    [self getData];
    
    // 设置播放器
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.playerManager = playerManager;
    /// 播放器相关
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.containerView];
    self.player.controlView = self.controlView;
    /// 设置退到后台继续播放
    self.player.pauseWhenAppResignActive = NO;
    
    @zf_weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        app.allowOrentitaionRotation = isFullScreen;
    };
    
    // 播放进度发生了改变
    self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
        @fk_strongify(self)
        self.currentTime = currentTime;
        self.duration = duration;
    };
    
    self.player.playerPlayStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerPlaybackState playState) {
        @fk_strongify(self)
        if (playState == 2) { // 退出或者暂停的时候记录播放的位置
            FKLastPlayMedia *info = [[FKLastPlayMedia alloc] init];
            info.media = self.currentModel;
            info.videoUrl = asset.assetURL.absoluteString;
            info.currentTime = fkFORMAT(@"%.2f", self.currentTime);
            info.duration = fkFORMAT(@"%2f", self.duration);
            [FKCacheTool saveLastPlayVideo:info];
        }
    };
    
    // 播放完成
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @zf_strongify(self)
        [self.player.currentPlayerManager replay];
        NSInteger index = [self playNextIndex];
        
        if (index < self.playUrls.count) {
            NSString *url = self.playUrls[index];
            playerManager.assetURL = [NSURL URLWithString:url];
            self.selectIndex = index;
            
            if (!self.player.isLastAssetURL) {
                NSDictionary *dict = self.dataSource[index];
                NSString *idStr = dict[@"id"];
                [FKCacheTool getMediaDetail:idStr complete:^(id data) {
                    self.currentModel = [ICMusicPlayModel mj_objectWithKeyValues:data];
                    self.nameLabel.text = self.currentModel.name;
                    self.desLabel.text = self.currentModel.describe;
                    [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeLandscape];
                }];
            } else {
                [self.player stop];
            }
        }
    };
    
    playerManager.assetURL = [NSURL URLWithString:self.currentModel.video_url];
    // 如果当前播放的是上次播放未结束的视频，则需要将播放位置设置到上次未结束的位置
    FKLastPlayMedia *media = [FKCacheTool lastPlayVideo];
    if (media && [self.currentModel.video_url isEqualToString:media.videoUrl]) {
        [playerManager seekToTime:media.currentTime.doubleValue completionHandler:nil];
    }
    [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeAutomatic];
}

- (void)initTopView{
    // 设置背景图
    UIImageView *backgroundImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    backgroundImgV.image = [UIImage imageNamed:@"playerBg"];
    backgroundImgV.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:backgroundImgV];
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
    bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [self.view addSubview:bgView];
    
    // 设置导航栏
    // 返回按钮
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,HY_StatusBar_Height,32,32)];
    backImage.image = [UIImage imageNamed:@"icon_fanhui"];
    [self.view addSubview:backImage];
    
    NSArray *titleArray = [self.currentModel.media_class_name componentsSeparatedByString:@"|"];
    CGFloat maxWidth = SCREEN_WIDTH - 110 - 46 - 50;
    if (titleArray.count >= 2) {
        CGFloat textWidth=[GC_OCTool getMaxWidthForLabel:titleArray[0] andFont:[UIFont systemFontOfSize: 16] andHeight:22 maxWidth:maxWidth] + 1;
        [self setTextLabel:titleArray[0] frame:CGRectMake(46,HY_StatusBar_Height,textWidth,22) font:[UIFont systemFontOfSize: 16]];
        [self setTextLabel:titleArray[1] frame:CGRectMake(46,HY_StatusBar_Height + 22,textWidth,10) font:[UIFont systemFontOfSize: 10]];
    } else if(titleArray.count == 1) {
        CGFloat textWidth=[GC_OCTool getMaxWidthForLabel:titleArray[0] andFont:[UIFont systemFontOfSize: 16] andHeight:22 maxWidth:maxWidth] + 1;
        [self setTextLabel:titleArray[0] frame:CGRectMake(46,HY_StatusBar_Height,textWidth,22) font:[UIFont systemFontOfSize: 16]];
        [self setTextLabel:@"" frame:CGRectMake(46,HY_StatusBar_Height + 22,textWidth,10) font:[UIFont systemFontOfSize: 10]];
    } else {
        [self setTextLabel:@"" frame:CGRectMake(46,HY_StatusBar_Height,0,22) font:[UIFont systemFontOfSize: 16]];
        [self setTextLabel:@"" frame:CGRectMake(46,HY_StatusBar_Height + 22,0,10) font:[UIFont systemFontOfSize: 10]];
    }
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, HY_StatusBar_Height + 4, 137 + 36, 22)];
    [self.view addSubview:backBtn];
    [backBtn  addTarget:self action:@selector(_leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
   
    // 右边的视频按钮
    self.videoBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 60, HY_StatusBar_Height + 7, 35, 22)];
    [self.videoBtn setTitle:@"视频" forState:UIControlStateNormal];
    self.videoBtn.titleLabel.font = fk_adjustFont(16);
    [self.videoBtn addTarget:self action:@selector(changeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.videoBtn setTitleColor:[UIColor colorWithHex:@"#FFFFFF"] forState:UIControlStateNormal];
    [self.view addSubview:self.videoBtn];
    
    // 右边的音频按钮
    self.audioBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 110, HY_StatusBar_Height + 7, 35, 22)];
    [self.audioBtn setTitle:@"音频" forState:UIControlStateNormal];
    self.audioBtn.titleLabel.font = fk_adjustFont(16);
    [self.audioBtn setTitleColor:[UIColor colorWithHex:@"#BBC4DA"] forState:UIControlStateNormal];
    [self.audioBtn addTarget:self action:@selector(changeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.audioBtn];
    
    // 滑块
    UIView *tabLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 42, 2)];
    [self.view addSubview:tabLineView];
    self.tabLineView = tabLineView;
    tabLineView.backgroundColor = [UIColor colorWithHex:@"#0091FF"];
    tabLineView.y = CGRectGetMaxY(self.videoBtn.frame) + 4;
    tabLineView.centerX = self.videoBtn.centerX;
    
    CGFloat x = 0;
    CGFloat y = CGRectGetMaxY(self.tabLineView.frame)+5;
    CGFloat w = CGRectGetWidth(self.view.frame);
    CGFloat h = w*9/16;
    self.containerView.frame = CGRectMake(x, y, w, h);
}

- (void)initMiddleView{
    CGFloat x = 0;
    CGFloat y = CGRectGetMaxY(self.videoBtn.frame);
    CGFloat w = SCREEN_WIDTH;
    CGFloat h = w*9/16;
    UIView  *view = [[UIView alloc]initWithFrame:CGRectMake(17,40 + y + h,wid(5),13)];
    view.backgroundColor = RBG(58,139,231);
    [self.view addSubview:view];
    
    // 名称
    UILabel* tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(view.frame) + 10, 33 + y + h,SCREEN_WIDTH-120, 27)];
    self.nameLabel = tipLabel;
    tipLabel.textColor=[UIColor whiteColor];
    tipLabel.font=[UIFont boldSystemFontOfSize:20];
    tipLabel.text = self.currentModel.name;;
    [self.view addSubview:tipLabel];
    
    // 收藏按钮
    UIButton *likeBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 42, HY_StatusBar_Height + 8, 32, 32)];
    [self.view addSubview:likeBtn];
    self.likeBtn = likeBtn;
    likeBtn.centerY = tipLabel.centerY;
    [likeBtn setBackgroundImage:[UIImage imageNamed:@"icon_Collect_default"] forState:UIControlStateNormal];
    [likeBtn setBackgroundImage:[UIImage imageNamed:@"icon_Collect_select"] forState:UIControlStateSelected];
    [likeBtn addTarget:self action:@selector(likeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:likeBtn];
    if ([FKCacheTool isLogin]) {
        self.likeBtn.hidden = NO;
    } else {
        self.likeBtn.hidden = YES;
    }
    
    // 描述
    UILabel* desLabel=[[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(tipLabel.frame) + 10, SCREEN_WIDTH-40, 50)];
    desLabel.textColor=[UIColor colorWithHex:@"#A9A9A9"];
    desLabel.numberOfLines = 0;
    desLabel.font = fk_adjustFont(14);
    desLabel.text = self.currentModel.describe;;
    [self.view addSubview:desLabel];
    self.desLabel = desLabel;
    
    // 标签title
    UILabel *tagTitleLabel=[[UILabel alloc] init];
    [self.view addSubview:tagTitleLabel];
    tagTitleLabel.left = 20;
    if (self.currentModel.describe.length == 0) {
        desLabel.hidden = YES;
        tagTitleLabel.top = CGRectGetMaxY(tipLabel.frame) + 10;
    }else{
        tagTitleLabel.top = CGRectGetMaxY(desLabel.frame) + 10;
        desLabel.hidden = NO;
    }
    tagTitleLabel.width = 48;
    tagTitleLabel.height = 20;
    tagTitleLabel.text = @"标签: ";
    tagTitleLabel.font = TitleFontSize(14);
    tagTitleLabel.textColor = [UIColor whiteColor];
    
    // 标签内容
    CGFloat tipWidth=[GC_OCTool getWidthForLabel:@"相关: " andFont:TitleFontSize(14) andHeight:hig(100)];
    CGFloat btnWidth = (SCREEN_WIDTH - 77 - 40 - 24 - 15) / 3.0;
    NSArray* lableArray = self.currentModel.lable;
//    lableArray = @[@{@"label": @"育儿"},
//                   @{@"label": @"今生无悔"},
//                   @{@"label": @"育儿"},
//                   @{@"label": @"幼师在线"},
//                   @{@"label": @"有道理的内容"}];
    CGFloat lableX = 68 + 20;
    NSInteger count = lableArray.count > 6 ? 6 : lableArray.count;
    CGFloat lableMaxY = 0;
    for(int i = 0; i < count; i++){
        NSInteger x = i % 3;
        NSInteger y = i / 3;
        NSDictionary *dict = lableArray[i];
        NSString *labelStr = dict[@"label"];
        CGFloat lableWidth=[GC_OCTool getWidthForLabel:labelStr andFont:TitleFontSize(12) andHeight:14] + 10;
        lableX = tipWidth + 20 + i * (lableWidth + 10);
        UIButton* btn = [[UIButton alloc]initWithFrame:CGRectMake(15 + CGRectGetMaxX(tagTitleLabel.frame) + x * (btnWidth + 12), CGRectGetMaxY(desLabel.frame) + 10 + y * (25 + 14), btnWidth, 25)];
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#D8D8D8" alpha:0.14]] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 12;
        btn.layer.masksToBounds = YES;
        [btn setTitle:labelStr forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:btn];
//        lableMaxY = CGRectGetMaxY(desLabel.frame) + 10 + y * (25 + 14);
        lableMaxY = CGRectGetMaxY(btn.frame) + 10 ;
    }
    if (lableArray.count == 0) {
        tagTitleLabel.hidden = YES;
        lableMaxY = CGRectGetMaxY(desLabel.frame) + 10;
    }
    
    // “排序”按钮
    UIButton *playOrderBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, lableMaxY, 32, 32)];
    [self.view addSubview:playOrderBtn];
    self.playOrderBtn = playOrderBtn;
    [playOrderBtn setImage:[UIImage imageNamed:@"playOrder_asc"] forState:UIControlStateNormal];
    [playOrderBtn setImage:[UIImage imageNamed:@"playOrder_desc"] forState:UIControlStateSelected];
    [playOrderBtn addTarget:self action:@selector(playOrderBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    // “播放模式”按钮
    UIButton *playModeBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 46,lableMaxY, 32, 32)];
    [self.view addSubview:playModeBtn];
    self.playModeBtn = playModeBtn;
    self.playStyle = 0;
    [playModeBtn setBackgroundImage:[UIImage imageNamed:@"playModel_loop"] forState:UIControlStateNormal];
    [playModeBtn addTarget:self action:@selector(playModeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // tableview
    [self.view addSubview:self.directoryTableView];
    self.directoryTableView.frame = CGRectMake(0, CGRectGetMaxY(playModeBtn.frame) + 15, SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(playModeBtn.frame) - 15);
    
    if ([FKCacheTool isLogin]) {
        UserModel *userModel = [FKCacheTool userInfo];
        if (userModel) {
            [self getCollectStatus:userModel.userinfo.user_id];
        } else {
            NSDictionary *info = [[NSUserDefaults standardUserDefaults] valueForKey:@"bnyt_userInfo"];
            if (info.count != 0) {
                //先加载本地
                UserModel *userModel = [[UserModel alloc] initWithDictionary:info[@"data"] error:nil];
                [Cache shared].userInfo = userModel;
                [self getCollectStatus:userModel.userinfo.id];
            }
        }
    }
}

- (UILabel *)setTextLabel:(NSString *)text frame:(CGRect)frame font:(UIFont *)font{
    UILabel *label = [[UILabel alloc] init];
    label.frame = frame;
    [self.view addSubview:label];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes: @{NSFontAttributeName: font,NSForegroundColorAttributeName: [UIColor whiteColor]}];
    label.attributedText = string;
    label.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:label];
    return label;
}

- (NSInteger)playNextIndex{
    if (self.playStyle == 0) { // 循环播放
        NSInteger nextIndex = self.selectIndex + 1;
        return (nextIndex > self.dataSource.count - 1) ? 0 : nextIndex;
    } else if (self.playStyle == 1){ // 单曲循环
        return self.selectIndex;
    } else { // 随机播放
        return arc4random_uniform((int32_t)self.dataSource.count);
    }
}

#pragma mark - action
- (void)_leftBtnAction{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)changeBtnClick:(UIButton *)btn{
    [self.audioBtn setTitleColor:[UIColor colorWithHex:@"#BBC4DA"] forState:UIControlStateNormal];
    [self.videoBtn setTitleColor:[UIColor colorWithHex:@"#BBC4DA"] forState:UIControlStateNormal];
    self.tabLineView.centerX = btn.centerX;
    [btn setTitleColor:[UIColor colorWithHex:@"#FFFFFF"] forState:UIControlStateNormal];
    if (btn == self.audioBtn) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)getCollectStatus:(NSString *)userId
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"media_id"] = self.currentModel.id;
    param[@"user_id"] = userId;
    [FKHttpTool postWithSuffix:@"/api/collect/checkCollect" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            NSInteger collectStatus = [result.data[@"collect_status"] integerValue];
            self.likeBtn.selected = collectStatus == 1;
        }
    } failure:nil];
}

- (void)likeBtnClick:(UIButton *)button {
    // 先判断用户是否登录
    @weakify(self)
    [FKLoginTool checkLogin:^{
        @strongify(self)
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"media_id"] = self.currentModel.id;
        UserModel *user = [FKCacheTool userInfo];
        param[@"user_id"] = user.userinfo.user_id;
        [FKHttpTool postWithSuffix:@"/api/collect/setCollect" param:param success:^(FKBaseResult *result) {
            if (result.isSuccess) {
                [SVProgressHUD showSuccessWithStatus:result.msg];
                if ([result.msg containsString:@"收藏成功"]) {
                    self.likeBtn.selected = true;
                } else {
                    self.likeBtn.selected = false;
                }
            }
        } failure:nil];
    }];
}

- (void)playOrderBtnClicked:(UIButton *)btn
{
    btn.selected = !btn.isSelected;
    if (btn.isSelected) {
        [SVProgressHUD showSuccessWithStatus:@"倒序播放"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"顺序播放"];
    }
    self.dataSource = [self.dataSource reverseObjectEnumerator].allObjects;
    [self.directoryTableView reloadData];
    
    // 重新设置选中的索引
    for (NSDictionary *dict in self.dataSource) {
        NSString *idStr = dict[@"id"] ? fkFORMAT(@"%@", dict[@"id"]) : nil;
        if ([idStr isEqualToString:self.currentModel.id]) {
            self.selectIndex = [self.dataSource indexOfObject:dict];
        }
    }
}

- (void)playModeBtnClick{
    NSArray *mode = @[@{@"text": @"循环播放", @"icon": @"playModel_loop"},
                      @{@"text": @"单条循环", @"icon": @"playModel_repeat"},
                      @{@"text": @"随机播放", @"icon": @"playModel_random"}];
    if (self.playStyle + 1 < mode.count) {
        self.playStyle = self.playStyle + 1;
    } else {
        self.playStyle = 0;
    }
    NSDictionary *currentMode = mode[self.playStyle];
    [SVProgressHUD showSuccessWithStatus:currentMode[@"text"]];
    [self.playModeBtn setBackgroundImage:[UIImage imageNamed:currentMode[@"icon"]] forState:UIControlStateNormal];
}

#pragma mark - 实现系统方法
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
 
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PlayVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"_directoryTableView" forIndexPath:indexPath];
    NSDictionary *dict = self.dataSource[indexPath.row];
    cell.titleLab.text = dict[@"name"];
    [Common updataTimerLableWithLable:cell.subTitleLab Second:[dict[@"video_num"] integerValue]];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.dataSource[indexPath.row];
    self.selectIndex = indexPath.row;
    if ([dict[@"video_url"] isEqualToString:self.currentModel.video_url]) {
        return;
    }

    NSString *idStr = dict[@"id"];
    if (idStr) {
        [FKCacheTool getMediaDetail:idStr complete:^(id data) {
            self.currentModel = [ICMusicPlayModel mj_objectWithKeyValues:data];
            self.nameLabel.text = self.currentModel.name;
            self.desLabel.text = self.currentModel.describe;
            NSString  *videoUrl = self.currentModel.video_url;
            videoUrl = [videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            self.playerManager.assetURL = [NSURL URLWithString: videoUrl];
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

#pragma mark - private
- (void)setSelectIndex:(NSInteger)selectIndex{
    _selectIndex = selectIndex;
    if (selectIndex == 0) {
        self.controlView.playShangyishouBtn.enabled = NO;
    }
       
    if(selectIndex == self.dataSource.count - 1){
        self.controlView.playXiayishouBtn.enabled = NO;
    }
    
    if (selectIndex > 0 && selectIndex < self.dataSource.count - 1) {
        self.controlView.playShangyishouBtn.enabled = YES;
        self.controlView.playXiayishouBtn.enabled = YES;
    }
    
    [self.directoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}

/** 点击上一首 */
- (void)playShangyishouBtnClick:(UIButton *)btn{
    self.selectIndex = self.selectIndex - 1 >= 0 ? self.selectIndex - 1 : 0;
    
    NSDictionary *dict = self.dataSource[self.selectIndex];
    if ([dict[@"video_url"] isEqualToString:self.currentModel.video_url]) {
        return;
    }
    NSString  *videoUrl = dict[@"video_url"];
    videoUrl = [videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    self.playerManager.assetURL = [NSURL URLWithString: videoUrl];
    [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeAutomatic];
    self.nameLabel.text = dict[@"name"];
}

/** 点击下一首 */
- (void)playXiayigeBtnClick:(UIButton *)btn{
    self.selectIndex = (self.selectIndex + 1) >= (self.dataSource.count - 1) ? self.selectIndex + 1 : 0;
    NSDictionary *dict = self.dataSource[self.selectIndex];
    if ([dict[@"video_url"] isEqualToString:self.currentModel.video_url]) {
        return;
    }
    NSString  *videoUrl = dict[@"video_url"];
    videoUrl = [videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    self.playerManager.assetURL = [NSURL URLWithString: videoUrl];
    
    [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeAutomatic];
    self.nameLabel.text = dict[@"name"];
}

- (HSCustomControlView *)controlView {
    if (!_controlView) {
        _controlView = [HSCustomControlView new];
        [_controlView.playXiayishouBtn addTarget:self action:@selector(playXiayigeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_controlView.playShangyishouBtn addTarget:self action:@selector(playShangyishouBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _controlView;
}

#pragma mark - lazy
- (NSArray *)playUrls
{
    if (!_playUrls) {
        _playUrls = [NSArray array];
    }
    return _playUrls;
}

- (UIImageView *)containerView {
    if (!_containerView) {
        _containerView = [UIImageView new];
//        [_containerView setImageWithURLString:kVideoCover placeholder:[ZFUtilities imageWithColor:[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1] size:CGSizeMake(1, 1)]];
        [_containerView setImageWithURLString:kVideoCover placeholder:[UIImage fk_imageWithColor:fkColor(220, 220, 220)]];
    }
    return _containerView;
}

- (UITableView *)directoryTableView{
    if (!_directoryTableView) {
        _directoryTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _directoryTableView.dataSource = self;
        _directoryTableView.delegate = self;
        _directoryTableView.showsVerticalScrollIndicator = NO;
        [_directoryTableView registerClass:[PlayVideoTableViewCell class] forCellReuseIdentifier:@"_directoryTableView"];
        _directoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _directoryTableView.backgroundColor = [UIColor clearColor];
    }
    return _directoryTableView;
}

#pragma mark - 网络请求
-(void)getData
{
    /**取消掉*/
    [_objectAFN cancelRequest];
    [self.objectAFN getUrlStr:[NSString stringWithFormat:@"%@/api/index/Directory?id=%@",server_addr,self.currentModel.id] finish:^(id  _Nonnull dataString) {
        
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
//        self.dataSource = dic[@"data"][@"data"];
        NSArray *list = dic[@"data"];
        NSMutableArray *datas = [NSMutableArray array];
        NSMutableArray *playUrls = [NSMutableArray array];
        for (NSDictionary *dict in list) {
            NSString *videoUrl =  dict[@"video_url"];
            if (videoUrl.length > 0) {
                [datas addObject:dict];
                videoUrl = [videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                [playUrls addObject:videoUrl];
            }
            if ([videoUrl isEqualToString:self.currentModel.video_url]) {
                self.selectIndex = datas.count - 1;
            }
        }
        self.dataSource = [NSArray arrayWithArray:datas];
        self.playUrls = playUrls;
        [self.directoryTableView reloadData];
        [self updateSelectState];
    } andError:^(NSError * _Nonnull error) {
        
    }];
}

- (void)updateSelectState
{
    [self.directoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}

@end
